package eu.scillman.net.tcp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;

import eu.scillman.net.INetEngine;

/**
 * The engine behind the client connection.
 * @author Jiri Waning
 */
/*internal*/ class ClientEngine implements INetEngine
{
	/** The actual connection with the remote host. **/
	private volatile Socket socket;
	
	/** The reader used to read from the connection. **/
	private volatile BufferedReader reader;
	
	public ClientEngine() {
		socket = null;
		reader = null;
	}
	
	/**
	 * Ensures clean up of the used resources.
	 */
	@Override
	public void finalize() throws Throwable {
		disconnect();
		super.finalize();
	}
	
	/**
	 * Connect to a remote host.
	 * @param address The IP-address of the remote host.
	 * @param port The port of the remote host.
	 */
	public void connect(InetAddress address, int port) {
		try {
			disconnect();
			socket = new Socket(address, port);
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (Exception ex) {
			System.out.println("Unable to connect to host.");
		}
	}
	
	/**
	 * Disconnect from the remote host.
	 */
	public void disconnect() {
		if (reader != null) {
			try {
				reader.close();
			} catch (Exception ex) {
				System.out.println(ex.getMessage());
			} finally {
				reader = null;
			}
		}

		if (socket != null) {
			try {
				if (!socket.isClosed()) {
					socket.close();
				}
			} catch (Exception ex) {
				System.out.println(ex.getMessage());
			} finally {
				socket = null;
			}
		}
	}
	
	/**
	 * Get the reader that can read from the connection.
	 * @return The reader that can read from the connection.
	 */
	public BufferedReader getReader() {
		return reader;
	}

	/**
	 * The monitoring thread.
	 */
	@Override
	public void run() {
		// TODO: Try to connect to the server.
	}

	@Override
	public void abort() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean hold() {
		// TODO Auto-generated method stub
		return false;
	}
}